
import React, { Component } from 'react';

import {Form, Input, Modal, Col, Row, Radio, Select, DatePicker, message, Switch, Button} from 'antd';
import { ygxxApi, institutionsApi, departmentsApi } from '@/services/basic';
import '@/layouts/handleList.css';
import moment from 'moment';
import {ButtonLock, InputCount} from "../../../components/BaseComponent/forms";
import "./style.css"

const Option = Select.Option;
class EditItem extends Component {
  constructor(props) {
    super(props);
    this.state = {
      id: undefined, // 标记保存的是哪一行的数据
      visible: false,
      institutionInitial: [],
      handler: undefined, // 当前正在执行的操作类型
      jktjmxList: [],
      List: [],
      size: 7,
      data: [],
      bmxx: [],
      gender: 1,
      userInfo: JSON.parse(sessionStorage.getItem('userInfo'))
    };
  }

  //关闭操作页面
  hideModal = () => {
    this.setState({
      id: undefined, //标记保存的是哪一行的数据
      visible: false,
      handler: undefined, //当前正在执行的操作类型
      gender: 1,

    });
    this.form.resetFields()
  };


  //弹出操作页面
  showModal = (handler, record) => {
    if (record) {//如果有record传过来 说明一定是查看或者更新操作
      const { id } = record;
      this.setState({ visible: true, id, handler })
      this.handleView(id);
    } else {//如果是新增操作 那直接展示弹出框 赋值操作类型
      this.setState({ visible: true, handler })
    }
  }

  // 表格页码改变
  sizechange = (result, msg) => {
    const List = Object.assign([], this.state.List)
    for (let index = 0; index < List.length; index++) {
      let msg = List[index].tjxmmc.split('||')
      if (msg.length > 1) {
        List[index].tjxmmc = msg[1]
        List[index].xxmc = msg[0]
      } else {
        List[index].xxmc = ""
      }
      List[index].rows = 1
    }
    for (let i = 0; i < List.length; i++) {
      for (let a = i + 1; a < List.length; a++) {
        if (List[i].rows !== 0 && i < List.length - 1 && List[i].tjxmmc === List[a].tjxmmc) {
          List[i].rows += 1
        } else if (List[i].rows > msg) {
          let count = i % msg
          List[i].rows = msg - count
          break
        } else {
          break
        }
        if (List[i].rows === msg - (i % msg)) {
          break
        }
      }
      if (List[i].rows > 1) {
        for (let j = 1; j < List[i].rows; j++) {
          List[i + j].rows = 0
        }
      }
    }
    this.setState({
      jktjmxList: List
    })
  }

  // //Modal框自带的确认操作
  handleOk = () => {
    const { handler } = this.state
    let newItem = this.form.getFieldsValue();
    newItem.rzsj =newItem.rzsj && moment(newItem.rzsj).format("YYYY-MM-DD hh:mm:ss");
    newItem.zzsj = newItem.zzsj && moment(newItem.zzsj).format("YYYY-MM-DD hh:mm:ss");
    newItem.lzsj =newItem.lzsj && moment(newItem.lzsj).format("YYYY-MM-DD hh:mm:ss");
    newItem.sfsx = Number(newItem.sfsx);
    const requestType = handler === 'create' ? 'post' : 'put'
    if (requestType === "put") {
			newItem.id = this.state.id;
		}
    this.form.validateFields().then(res => {
      ygxxApi[requestType](newItem)
        .then((response) => {
          if (response.code === '1') {
            this.form.resetFields()
            this.hideModal();
            this.props.editItemDone();
            message.success('操作成功');
          } else if (response.code === '0') {
            message.warning("111111111")
          } else {
            message.error(`操作失败${response.msg}`)
          }
        })
    })
      .catch(error => {
        // eslint-disable-next-line
        console.dir(error)
      })
  };

  /**
   * @author: 陈科引
   * @param {Strng} xm 姓名
   * @param {Strng} xb 性别
   * @param {Number} xb 年龄
   * @param {Object} jktjmxList 体检项目内容
   * @description: 查看单条
   */
  // handleView = (id) => {
  //   if (id) {
  //     ygxxApi.get(id).then((res) => {
  //       // let size=7
  //       const { jktjmxList, nl, xb, xm, tjrq, tjjgmc } = res
  //       for (let index = 0; index < jktjmxList.length; index++) {
  //         let msg = jktjmxList[index].tjxmmc.split('||')
  //         if (msg.length > 1) {
  //           jktjmxList[index].tjxmmc = msg[1]
  //           jktjmxList[index].xxmc = msg[0]
  //         } else {
  //           jktjmxList[index].xxmc = ""
  //         }
  //         jktjmxList[index].rows = 1
  //       }
  //       this.setState({
  //         jktjmxList: jktjmxList, List: res.jktjmxList
  //       }, () => this.sizechange(null, 7))

  //       this.form.setFieldsValue({
  //         nl, xb, xm, tjrq, tjjgmc
  //       });
  //     });
  //   }
  // };

  //公司机构输入时触发
  onInstitutionSearch = (value) => {
    if (value.charCodeAt(value.length - 1) === 32) {
      value = value.trim();
      institutionsApi.search({ search: `${value}` }).then((res) => {
        let institutionInitial = res.records.map((item) => (
          <Option key={item.yybm} value={item.yybm}>
            {item.yymc}
          </Option>
        ));
        this.setState({
          bmxx: [],
          bmid: '',
          institutionInitial: institutionInitial,
        });
      });
    }
  };

  //部门输入时触发
  onBmxxSearch = (value) => {
    const { yybm } = this.form.getFieldsValue()
    if (value.charCodeAt(value.length - 1) === 32) {
      value = value.trim();
      departmentsApi.search({ search: `${value}`, yybm: yybm }).then((res) => {
        let bmxx = res.records.map((item) => (
          <Option key={item.id} value={item.id}>
            {item.ksmc}
          </Option>
        ));
        this.setState({
          bmxx: bmxx,
        });
      });
    }
  };


  //查看单条
  handleView = (id) => {
    institutionsApi.search({ search: `` }).then((res) => {
      let institutionInitial = res.records.map((item) => (
        <Option key={item.yybm} value={item.yybm}>
          {item.yymc}
        </Option>
      ));
      this.setState({
        institutionInitial: institutionInitial,
      });
    });
    departmentsApi.search({ search: `` }).then((res) => {
      let bmxx = res.records.map((item) => (
        <Option key={item.id} value={item.id}>
          {item.ksmc}
        </Option>
      ));
      this.setState({
        bmxx: bmxx,
      });
    });
    if (id) {
      // this.onYljgzSearch();
      ygxxApi.get(id)
        .then((res) => {
          let { xm, xb, yymc, lxdh, sfz, zw, yybm, gh, rzsj, zzsj, lzsj, ztbz, tyyy, xz, yhkh, bmid, gsid, sflz,sjmc,mrlzs,sfsx } = { ...res.data };
          rzsj = rzsj && moment(rzsj);
          zzsj = zzsj && moment(zzsj);
          lzsj = lzsj && moment(lzsj);
          sfsx = !!sfsx;
          let set = { xm, xb, yymc, lxdh, sfz, zw, yybm, gh, rzsj, zzsj, lzsj, ztbz, tyyy, xz, yhkh, bmid, gsid, sflz ,sjmc,mrlzs,sfsx};
          this.form.setFieldsValue({ ...set });
          this.setState({
            visible: true,
            gender: set.sjmc,
          })
        })
    }
  }


  render() {
    const { handler, visible } = this.state;
    return (
      <div className='handle-header'>
        <Modal
          title=''
          visible={visible}
          onCancel={this.hideModal}
          width='1000px'
          style={{ top: 60 }}
          maskClosable={false}
          className='handleList '
          footer={this.state.handler === "view" ? null : [
            <Button onClick={this.hideModal}>取消</Button>,
            <ButtonLock onClick={this.handleOk} type="primary">确定</ButtonLock>
          ]}
          // footer={this.props.modalfoot(handler, this.hideModal, this.handleOk)}
        >
          <div className='formHeader'>
            <span className='handle-title'>{`${handler === 'view' ? '查看' : handler === 'create' ? '新增' : '更新'}人员信息`}</span>
          </div>

          <Form autoComplete='off' className='antrow10 minw100' ref={(form) => (this.form = form)} >
            <Row gutter={8}>
              <Col span={24}>
                <div className='extraInfouserlist' style={{ marginTop: '0' }}>人员信息</div>
              </Col>
            </Row>
            <Row gutter={8}>
              <Col span={8}>
                <Form.Item
                  label='姓名'
                  name='xm'
                  rules={[
                    { required: true, message: '此为必填项' }
                  ]}
                  getValueFromEvent={(event) => event.target.value.replace(/\s+/g, '')}
                >
                  <Input
                    allowClear
                    placeholder='请输入'
                  />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="性别" name="xb" rules={[{ required: true, message: "此为必填项" }]}>
                  {handler === "create" ?
                    <Radio.Group onChange={this.change}>
                      <Radio value={1}>男</Radio>
                      <Radio value={0}>女</Radio>
                    </Radio.Group>
                    :
                    <Radio.Group onChange={this.change} disabled>
                      <Radio value={1}>男</Radio>
                      <Radio value={0}>女</Radio>
                    </Radio.Group>}
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item
                  label='联系电话'
                  name='lxdh'
                  rules={[
                    { required: true, message: '此为必填项' }
                  ]}
                >
                  <Input
                    allowClear
                    placeholder='请输入'
                  />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={8}>
              <Col span={8}>
                <Form.Item
                  label='身份证'
                  name='sfz'
                  rules={[
                    { required: true, message: '此为必填项' }
                  ]}
                >
                  <Input

                    allowClear
                    placeholder='请输入'
                  />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="职务"
                  name="zw"
                  initialValue={this.state.gender}
                >
                  <Select
                    disabled={handler === 'view' ? true : false}
                    allowClear={handler === 'view' ? false : true}
                    placeholder="请选择职务">
                    {
                      this.props.bookRender('zw')
                    }
                  </Select>
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item
                  label='工号'
                  name='gh'
                  rules={[
                    { required: true, message: '此为必填项' }
                  ]}
                >
                  <Input
                    allowClear
                    placeholder='请输入'
                  />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item
                  label='入职时间'
                  name='rzsj'
                  rules={[
                    { required: true, message: '此为必填项' }
                  ]}
                >
                  <DatePicker format={"YYYY-MM-DD"} />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item
                  label='转正时间'
                  name='zzsj'
                  rules={[
                    { required: true, message: '此为必填项' }
                  ]}
                >
                  <DatePicker format={"YYYY-MM-DD"} />
                </Form.Item>
              </Col>

              <Col span={8}>
                <Form.Item label="是否离职" name="sflz" rules={[{ required: true, message: "此为必填项" }]}>
                  {handler === "create" ?
                    <Radio.Group onChange={this.change}>
                      <Radio value={1}>在职</Radio>
                      <Radio value={0}>离职</Radio>
                    </Radio.Group>
                    :
                    <Radio.Group onChange={this.change} disabled>
                      <Radio value={1}>在职</Radio>
                      <Radio value={0}>离职</Radio>
                    </Radio.Group>}
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item
                  label='离职时间'
                  name='lzsj'

                >
                  <DatePicker format={"YYYY-MM-DD"} />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item
                  label='薪资'
                  name='xz'
                  rules={[
                    { message: '此为必填项' }
                  ]}
                >
                  <Input
                    allowClear
                    placeholder='请输入'
                  />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item
                  label='银行卡号'
                  name='yhkh'
                  rules={[
                    { message: '此为必填项' }
                  ]}
                >
                  <Input
                    allowClear
                    placeholder='请输入'
                  />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label='公司名称'
                  name="yybm"
                >
                  <Select
                    allowClear
                    onSearch={this.onInstitutionSearch}
                    placeholder="请选择公司"
                    filterOption={false}
                    showSearch={true}
                    showArrow={false}
                  >
                    {this.state.institutionInitial}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label='部门名称'
                  name="bmid"
                >
                  <Select
                    allowClear
                    onSearch={this.onBmxxSearch}
                    placeholder="请选择部门"
                    filterOption={false}
                    showSearch={true}
                    showArrow={false}
                  >
                    {this.state.bmxx}
                  </Select>
                </Form.Item>
              </Col>
              <InputCount min={0}></InputCount>

              <Col span={8}>
                <Form.Item label='是否上限' name="sfsx" valuePropName="checked">
                  <Switch checkedChildren="是" unCheckedChildren="否"/>
                </Form.Item>

              </Col>
            </Row>
          </Form>

        </Modal>
      </div >
    );
  }
}
export default EditItem;

